package com.example.authserver.controller;

import com.alibaba.fastjson.TypeReference;
import com.example.authserver.feign.MemberFeignService;
import com.example.authserver.feign.SmsFeignService;
import com.example.authserver.vo.UserLoginVo;
import com.example.authserver.vo.UserRegisterVo;
import com.example.common.constant.AuthServerConstant;
import com.example.common.exception.BizCodeEnum;
import com.example.common.utils.R;
import com.example.common.vo.MemberResponseVo;
import com.fasterxml.jackson.annotation.ObjectIdGenerators;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Controller
public class LoginController {
    @Autowired
    RedisTemplate redisTemplate;
    @Autowired
    SmsFeignService smsFeignService;
    @Autowired
    MemberFeignService memberFeignService;
    @GetMapping("/sms/sendCode")
    @ResponseBody
    public R sendCode(@RequestParam("phone") String phone){
        ValueOperations<String,String> valueOperations = redisTemplate.opsForValue();
        String phoneIndex=AuthServerConstant.SMS_CODE_CACHE_PREFIX + phone;
        String s = valueOperations.get(phoneIndex);
        if(StringUtils.isNotEmpty(s)){
            long time = Long.parseLong(s.split("_")[1]);
            if(System.currentTimeMillis()-time<60000){
                return R.error(BizCodeEnum.SMS_CODE_CACHE_PREFIX.getCode(), BizCodeEnum.SMS_CODE_CACHE_PREFIX.getMsg());
            }
        }
        redisTemplate.delete(phoneIndex);
        String code = UUID.randomUUID().toString().substring(0, 5);
        valueOperations.set(phoneIndex,code+"_"+System.currentTimeMillis(),10, TimeUnit.MINUTES);
        smsFeignService.sendCode(phone,code);
        return R.ok();
    }
    @PostMapping("/register")
    public String register(@Valid UserRegisterVo userRegisterVo, BindingResult result,
                           RedirectAttributes redirectAttributes){
        Map<String, String> errors =new HashMap<>();
        if(result.hasErrors()){
            errors = result.getFieldErrors().stream().collect(Collectors.toMap(FieldError::getField,
                    FieldError::getDefaultMessage));
            redirectAttributes.addFlashAttribute("errors",errors);
            return "redirect:http://auth.gulimall.com/reg.html";
        }
        else{
            String redisCode = (String) redisTemplate.opsForValue().get(AuthServerConstant.SMS_CODE_CACHE_PREFIX
                    + userRegisterVo.getPhone());
            String code=redisCode.split("_")[0];
            if(StringUtils.isNotEmpty(code)&&code.equalsIgnoreCase(userRegisterVo.getCode())){
                redisTemplate.delete(AuthServerConstant.SMS_CODE_CACHE_PREFIX+userRegisterVo.getPhone());
                R r=memberFeignService.register(userRegisterVo);
                if((int)r.get("code")==0){
                    return "redirect:http://auth.gulimall.com/login.html";
                }
                else{
                    errors.put("msg",r.getData("msg",new TypeReference<String>(){}));
                    redirectAttributes.addFlashAttribute("errors",errors);
                    return "redirect:http://auth.gulimall.com/reg.html";
                }

            }
            else{
                errors.put("code","验证码错误");
                redirectAttributes.addFlashAttribute("errors",errors);
                return "redirect:http://auth.gulimall.com/reg.html";
            }
        }
    }
    @RequestMapping("/login")
    public String login(UserLoginVo vo, RedirectAttributes redirectAttributes, HttpSession session){
        R login = memberFeignService.login(vo);
        if((int)login.get("code")==0){
            MemberResponseVo responseVo = login.getData("data", new TypeReference<MemberResponseVo>() {
            });
            session.setAttribute(AuthServerConstant.LOGIN_NAME,responseVo);
            return "redirect:http://gulimall.com/";
        }
        else{
            String msg = login.getData("msg", new TypeReference<String>() {
            });
            Map<String, String> errors = new HashMap<>();
            errors.put("msg", msg);
            redirectAttributes.addFlashAttribute("errors", errors);
            return "redirect:http://auth.gulimall.com/login.html";
        }
    }
    @GetMapping(value = "/login.html")
    public String loginPage(HttpSession session) {

        //从session先取出来用户的信息，判断用户是否已经登录过了
        Object attribute = session.getAttribute(AuthServerConstant.LOGIN_NAME);
        //如果用户没登录那就跳转到登录页面
        if (attribute == null) {
            return "login";
        } else {
            return "redirect:http://gulimall.com";
        }

    }
}
